package com.imooc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * <h1>跨域</h1>
 *
 * @author : dzj
 * @create: 2022-02-14 23:27
 */
@Configuration
public class CorsConfig {
    public CorsConfig() {
    }
    @Bean
    public CorsFilter corsFilter() {
        // 1. 配置cors配置信息
        CorsConfiguration config = new CorsConfiguration();
     //   config.addAllowedOrigin("http://localhost:8080");  // 建议进行部分限制
        config.addAllowedOrigin("*");
        config.setAllowCredentials(true);// 设置是否发送cookie等信息
      config.addAllowedMethod("*"); //设置允许的请求方式
        config.addAllowedHeader("*");  //设置允许的header

        // 2.为url添加映射路径
        UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource();
        corsSource.registerCorsConfiguration("/**",config);

        //返回重新定义好的source
        return  new CorsFilter(corsSource);


    }
}
